import { app, BrowserWindow, Notification, screen, ipcMain, globalShortcut, dialog, Menu, nativeImage, Tray } from 'electron';
import path from 'path';
import { QuickStart } from './quickStart';
import { IItem } from '../type';

const WindowWidth = 500;

let mainWindow: BrowserWindow | null;
let quickStart: QuickStart | null;
let tray: Tray | null;

// 确保只有一个实例运行
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) { // 已经有实例在运行
    app.quit();
}
else {
    // 当用户尝试启动第二个应用时，显示界面
    app.on('second-instance', (e, c, w) => {
        mainWindow?.show();
    });
}

app.whenReady().then(() => {
    // 创建 QuickStart
    quickStart = new QuickStart();
    quickStart.load();

    createTray();

    // 监控渲染进程的事件
    ipcMain.handle('searchContextChange', searchContentChange);
    ipcMain.handle('setWindowHeight', (event, height: number) => {
        if (mainWindow == null) return;
        mainWindow.setBounds({ ...mainWindow.getBounds(), height: height });
    });
    ipcMain.handle('notification', (event, title: string, body: string) => { new Notification({ title: title, body: body }).show() });
    ipcMain.handle('hideWindow', (event) => { mainWindow?.hide(); });
    ipcMain.handle('showMessageBox', (event, opt) => { dialog.showMessageBox(opt); });
    ipcMain.handle('getSelectionIndex', event => quickStart?.getSelectionIndex());

    createWindow();
    quickStart.onReload = () => {
        mainWindow?.webContents.send('resetFace');
    }

    globalShortcut.register('Super+`', () => {
        mainWindow?.show();
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit(); // 退出应用
    }
});

app.on('quit', () => {
    mainWindow = null;
    quickStart = null;
    tray = null;

    globalShortcut.unregisterAll();
});

function createWindow() {
    mainWindow = new BrowserWindow({
        width: WindowWidth,
        x: (screen.getPrimaryDisplay().size.width - WindowWidth) / 2, // 居中
        y: 250,
        show: false,
        frame: false,
        skipTaskbar: true,
        alwaysOnTop: true,
        title: 'QuickStart',
        icon: path.join(__dirname, '../../public/icon.png'),
        webPreferences: {
            preload: path.join(__dirname, '../preload/preload.js'),
        }
    });

    createMenu();

    mainWindow.webContents.on('before-input-event', (e, input) => {
        if (input.key === 'ArrowUp') {
            upMoveSelection();
            e.preventDefault();
        }
        else if (input.key === 'ArrowDown') {
            downMoveSelection();
            e.preventDefault();
        }
    });

    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));

    mainWindow.on('show', () => {
        mainWindow?.webContents.send('mainWindowShow');
    });

    mainWindow.on('hide', () => {
        quickStart?.resetSearch();
        mainWindow?.webContents.send('resetFace');
    });

    // mainWindow?.webContents.openDevTools({ mode: 'undocked' });
};

function searchContentChange(event: any, content: string): IItem[] {
    if (quickStart == null || mainWindow == null) return [];
    let items = quickStart.search(content);
    quickStart.resetSelection();
    return items;
}

function createMenu() {
    let menuTemp = [
        {
            label: '向上移动选择',
            click: upMoveSelection,
            accelerator: 'CommandOrControl+k'
        },
        {
            label: '向下移动选择',
            click: downMoveSelection,
            accelerator: 'CommandOrControl+j'
        },
        {
            label: '运行',
            click: () => {
                quickStart?.execSelection();
                mainWindow?.hide();
            },
            accelerator: 'Enter'
        },
        {
            label: '隐藏窗口',
            click: () => { mainWindow?.hide(); },
            accelerator: 'Esc'
        },
    ];
    let menu = Menu.buildFromTemplate(menuTemp);
    Menu.setApplicationMenu(menu);
}

/**创建托盘菜单 */
function createTray() {
    const icon = nativeImage.createFromPath(path.join(__dirname, '../../public/icon.png'));
    tray = new Tray(icon);
    tray.on('click', () => { app.quit(); });
}

function upMoveSelection() {
    quickStart?.upMoveSelection();
    mainWindow?.webContents.send('selectionChange', quickStart?.getSelectionIndex());
}

function downMoveSelection() {
    quickStart?.downMoveSelection();
    mainWindow?.webContents.send('selectionChange', quickStart?.getSelectionIndex());
}
